# -*- coding: utf-8 -*-
import cv2
import numpy as np
import sys
import os

def mkdir(path):

 
    # 去除首位空格
    path=path.strip()
    # 去除尾部 \ 符号
    path=path.rstrip("\\")
 
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists=os.path.exists(path)
 
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path) 
 
        print path+' 创建成功'
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print path+' 目录已存在'
        return False

if __name__ == "__main__":
    print 'Total:', len(sys.argv)
    print 'list:', str(sys.argv)

    path = os.getcwd()
    print (os.listdir(path))
    str_files = os.listdir(path)
    # exit()
    # for pic in sys.argv:
    for pic in str_files:
        print(pic)
        str_name = pic.split('.')
        # print(len(str_name))
        # print(str_name)
        # print(str_name[1])
        # print(pic)
        if(len(str_name) != 2 or str_name[1] != "jpg"):
            continue

        if(pic != "cat.jpg"):
            continue
        img_path = pic
        # image = cv2.imread(img_path,-1)
        image = cv2.imread(img_path)
        img_nearest = image
        img_nearest = cv2.resize(image, (50, 50), cv2.INTER_CUBIC)
        # cv2.imwrite(str_name[0]+'_cubic.png', img_nearest)
        img_size = img_nearest.shape[:2]
        directory  =  "out/"
        mkdir(directory)
        filename = str_name[0] + ".c"
        print(str_name)
        file = open(directory + filename,"w+")

        file.write("#include \"lvgl.h\"\n\n")

        file.write("const uint8_t " + str_name[0] + "[] = {\n")
        file.write("  ")
        cnt =  0
        for i in range(0,img_size[0]):
            for j in range(0,img_size[1]):
                r = img_nearest[i,j][0]
                g = img_nearest[i,j][1]
                b = img_nearest[i,j][1]
                co = ((b & 0xF8) << 8) | ((g & 0xFC) << 3) | (r >> 3)
                # for di in img_nearest[i,j]:
                file.write("0x%02X," % (co>>8))
                file.write("0x%02X," % (co&0xFF))
                cnt = cnt + 1
                if (cnt % 10 == 0):
                    file.write("\n  ")

        file.write("\n};")
        file.write("\n")
        file.write("\n")

        struct_name = "pic_" + str_name[0]
        file.write("const lv_img_dsc_t " + struct_name + " = {\n")
        file.write("    .header.always_zero = 0,\n")
        file.write("    .header.w = " + str(img_size[1]) + ",\n")
        file.write("    .header.h = " + str(img_size[0]) + ",\n")
        file.write("    .data_size = " + str(img_size[0]*img_size[1]) + ",\n")
        file.write("    .header.cf = LV_IMG_CF_TRUE_COLOR_ALPHA,\n")
        file.write("    .data = " + str_name[0] + ",\n")
        file.write("}; \n")
        file.close()
        print(filename,img_size)



